package com.aisino.inveli.vinda.controller;

import com.aisino.inveli.vinda.VindamanagerApplication;
import com.aisino.inveli.vinda.entity.Customer;
import com.aisino.inveli.vinda.service.CustomerService;
import com.aisino.inveli.vinda.task.CustomerTask;
import com.aisino.inveli.vinda.utils.AlertUtil;
import com.aisino.inveli.vinda.utils.ProgressUtil;
import de.felixroske.jfxsupport.FXMLController;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.image.Image;
import javafx.stage.FileChooser;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.Window;
import javafx.util.Callback;
import org.springframework.data.domain.Page;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

/**
 * @author leifeng
 * @Date 2017-11-22
 **/
@FXMLController
public class CustomerController implements Initializable{

    @FXML
    private TextField keyword;
    @FXML
    private TableView<Customer> customerView;
    @FXML
    private TableColumn<Customer,Integer> id;
    @FXML
    private TableColumn<Customer,String> cusName;
    @FXML
    private TableColumn<Customer,String> regNumber;
    @FXML
    private TableColumn<Customer,String> bank;
    @FXML
    private TableColumn<Customer,String> addAndTel;
    @FXML
    private TableColumn<Customer,String> email;
    @FXML
    private Pagination page;

    //-------------------------Service------------------------------
    @Resource
    private CustomerService customerService;

    /**
     * 退出当期窗体操作，返回主界面
     */
    @FXML
    public void exitAction(){
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/view/main.fxml"));
        VindamanagerApplication.showView(fxmlLoader);
    }

    /**
     * 导入数据操作
     * @param event
     */
    @FXML
    public void exportAction(ActionEvent event){
        // 1.获取文件所属窗体
        Window window  = ((Button)event.getSource()).getScene().getWindow();
        // 2.弹出文件选择框
        FileChooser fileChooser = new FileChooser();
        // 2.1文件筛选
        List<String> filter = new ArrayList<>();
        filter.add("*.txt");
        FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("txt files (*.txt)", filter);
        fileChooser.getExtensionFilters().add(extFilter);
        fileChooser.setTitle("选择打开文件");
        File file = fileChooser.showOpenDialog(window);
        // 3.判断设置路径
        if(file != null){
            CustomerTask customerTask = new CustomerTask(file,customerService);
            customerTask.valueProperty().addListener((observable, oldValue, newValue) ->{
                if (newValue) {
                    // 3.3弹出设置成功提示
                    AlertUtil.showInfoAlert("","保存成功",window);
                }else {
                    AlertUtil.showErrAlert("",window,"保存失败");
                }
            });
            ProgressUtil progressUtil = new ProgressUtil(customerTask, window, "保存数据中，请稍后");
            progressUtil.activateProgressBar();
        }
    }

    /**
     * 搜索用户
     */
    @FXML
    public void searchAction(){
        showList(0);
    }

    /**
     * 添加用户
     * @param event
     */
    @FXML
    public void addAction(ActionEvent event){
        Stage stage = new Stage();
        Parent root;
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getClassLoader().getResource("view/addCustomer.fxml"));
        try {
            root = fxmlLoader.load();
            AddCustomerController controller = fxmlLoader.getController();
            controller.initData(customerService);
            stage.setScene(new Scene(root));
            stage.setTitle("添加客户信息");
            stage.initModality(Modality.APPLICATION_MODAL);
            stage.setResizable(false);
            stage.getIcons().add(new Image("/image/icon.png"));
            stage.initOwner(((Node) event.getSource()).getScene().getWindow());
            stage.show();
            stage.setOnHidden(t-> showList(0));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 删除用户
     * @param event
     */
    @FXML
    public void delAction(ActionEvent event){
        Window window = ((Button) event.getSource()).getScene().getWindow();
        Customer customer = customerView.getSelectionModel().getSelectedItem();
        if (customer == null){
            AlertUtil.showErrAlert("",window,"请选择一条记录");
        } else {
            if (AlertUtil.confirmAlert("确定删除此记录？",window,"")){
                customerService.delCustomerById(customer.getId());
                AlertUtil.showInfoAlert("","删除成功",window);
                showList(0);
            }
        }
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        customerView.setEditable(true);
        id.setCellValueFactory(new PropertyValueFactory<>("id"));
        cusName.setCellValueFactory(new PropertyValueFactory<>("cusName"));
        regNumber.setCellValueFactory(new PropertyValueFactory<>("regNumber"));
        bank.setCellValueFactory(new PropertyValueFactory<>("bank"));
        addAndTel.setCellValueFactory(new PropertyValueFactory<>("addAndTel"));
        email.setCellValueFactory(new PropertyValueFactory<>("email"));
        page.setPageFactory(param -> {showList(param);return customerView;});

        cusName.setCellFactory(TextFieldTableCell.forTableColumn());
        cusName.setOnEditCommit(event -> {
            String newValue = event.getNewValue();
            Customer customer = customerView.getSelectionModel().getSelectedItem();
            customer.setCusName(newValue);
            customerService.save(customer);
        });
        regNumber.setCellFactory(TextFieldTableCell.forTableColumn());
        regNumber.setOnEditCommit(event -> {
            String newValue = event.getNewValue();
            Customer customer = customerView.getSelectionModel().getSelectedItem();
            customer.setRegNumber(newValue);
            customerService.save(customer);
        });
        bank.setCellFactory(TextFieldTableCell.forTableColumn());
        bank.setOnEditCommit(event -> {
            String newValue = event.getNewValue();
            Customer customer = customerView.getSelectionModel().getSelectedItem();
            customer.setBank(newValue);
            customerService.save(customer);
        });
        addAndTel.setCellFactory(TextFieldTableCell.forTableColumn());
        addAndTel.setOnEditCommit(event -> {
            String newValue = event.getNewValue();
            Customer customer = customerView.getSelectionModel().getSelectedItem();
            customer.setAddAndTel(newValue);
            customerService.save(customer);
        });
        email.setCellFactory(TextFieldTableCell.forTableColumn());
        email.setOnEditCommit(event -> {
            String newValue = event.getNewValue();
            Customer customer = customerView.getSelectionModel().getSelectedItem();
            customer.setEmail(newValue);
            customerService.save(customer);
        });

    }

    /**
     * 分页显示
     * @param param
     */
    private void showList(Integer param) {
        String keywordText = keyword.getText();
        Page<Customer> cusList = customerService.findAllCustomer(param,keywordText);
        ObservableList<Customer> list = FXCollections.observableArrayList();
        for (Customer cus:cusList.getContent()) {
            list.add(cus);
        }
        customerView.setItems(list);
        page.setPageCount(cusList.getTotalPages());
    }
}
